import request from '@/utils/request'
import { removeTokenInfo } from '@/utils/storage'
import { SAVE_USER, EDIT_USER } from '../action_types/profile'

export const saveUserInfo = (payload) => {
  return {
    type: SAVE_USER,
    payload,
  }
}

/**
 * 获取用户自己的信息
 * @returns promise
 */
export const getUser = () => {
  return async (dispatch) => {
    const res = await request({
      url: '/user',
      method: 'GET',
    })
    // console.log(res)
    dispatch(saveUserInfo(res.data))
  }
}

export const saveProfile = (payload) => {
  return {
    type: EDIT_USER,
    payload,
  }
}

/**
 * 获取用户个人资料
 * @returns promise
 */
export const editUser = () => {
  return async (dispatch) => {
    const res = await request({
      url: '/user/profile',
      method: 'GET',
    })
    // console.log(res)
    dispatch(saveProfile(res.data))
  }
}

/**
 * 修改用户信息
 * @param {*} name 需要修改的类型
 * @param {*} value 需要修改的值
 * @returns
 */
export const editUserInfo = (name, value) => {
  return async (dispatch) => {
    const res = await request.patch('user/profile', { [name]: value })
    console.log(res)
    // 如果后端更新成功，就更新redux数据
    if (res.message === 'OK') {
      dispatch(editUser())
    }
  }
}

/**
 * 修改用户头像
 * @param {*} fd 图片上传的文件
 * @returns
 */
export const editPhoto = (fd) => {
  return async (dispatch) => {
    const res = await request.patch('/user/photo', fd)
    // 如果后端更新成功，就更新redux数据
    if (res.message === 'OK') {
      dispatch(editUser())
    }
  }
}

// 退出登录
export const logout = () => {
  return (dispatch) => {
    // 清除token
    removeTokenInfo()
    // 清空redux数据
    dispatch({
      type: 'profile/logout',
    })
  }
}
